package leetcodev1.字符串;

import leetcodev1.链表.Solution;

import java.util.*;

public class LeetCode49 {

    //可以利用计数进行合并 重复元素怎么办..
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ret = new ArrayList<>();
        HashMap<String, List<String>> dict = new HashMap<>();
        for (String str : strs) {
            int[] tmp = new int[26];
            int length = str.length();
            for (int i = 0; i < length; i++) {
                tmp[str.charAt(i) - 'a']++;
            }
            String countString = Arrays.toString(tmp);
            if (!dict.containsKey(countString)) {
                ArrayList<String> list = new ArrayList<>();
                ret.add(list);
                dict.put(countString, list);
            }
            dict.get(countString).add(str);
        }
        return ret;
    }
}

class Answer49{
    //计数
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            int[] counts = new int[26];
            int length = str.length();
            for (int i = 0; i < length; i++) {
                counts[str.charAt(i) - 'a']++;
            }
            // 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串，作为哈希表的键
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 26; i++) {
                if (counts[i] != 0) {
                    sb.append((char) ('a' + i));
                    sb.append(counts[i]);
                }
            }
            String key = sb.toString();
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }

    //排序
    public List<List<String>> groupAnagrams1(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        //!!!注意
        //可以直接把value放入数组中
        return new ArrayList<List<String>>(map.values());
    }
}
